package com.ctparking;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Path("/parking")
public class Server {
	
	static Database db = new Database();
	
	// This method is called if TEXT_PLAIN is request
	@GET
	@Produces(MediaType.TEXT_PLAIN)
	public String sayPlainTextHello() {
		
		JSONArray jarray = new JSONArray();
		JSONObject parkingJSON = new JSONObject();
		
		for(int i = 0; i < db.parkingList.size(); i++){
			parkingJSON.put("nome", db.parkingList.get(i).getNome());
			parkingJSON.put("posti_disponibili", String.valueOf(db.parkingList.get(i).getPosti()));
			parkingJSON.put("indirizzo", db.parkingList.get(i).getIndirizzo());
			parkingJSON.put("latitudine", String.valueOf(db.parkingList.get(i).getLatitudine()));
			parkingJSON.put("longitudine", String.valueOf(db.parkingList.get(i).getLongitudine()));
			jarray.add(parkingJSON);
		}
		return jarray.toString();
	}

	// This method is called if XML is request
	@GET
	@Path("/1")
	@Produces(MediaType.TEXT_XML)
	public String sayXMLHello() {
		return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
	}

	// This method is called if HTML is request
	@GET
	@Produces(MediaType.TEXT_HTML)
	public String sayHtmlHello() {
		return "<html> " + "<title>" + "Hello Jersey" + "</title>"
				+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
	}
	
	@GET
	@Path("/dec/{name}/")
	public String Decrementa(@PathParam("name") String nome){
		String out = "Nessun Parcheggio trovato con nome " + nome;
		boolean continua = true;
		int i = 0;
		while(i < db.parkingList.size() && continua){
			 if(db.parkingList.get(i).getNome().equals(nome)){
				 continua = false;
				 db.parkingList.get(i).decPosti();
				 out = generatePrenotation(nome);
				 Timer timer = new Timer();
				 TimerTask task = new Worker();
				 timer.schedule(task,3900000); //Dopo 65 minuti avvio l'evento per annullare la prenotazione
			 }
			 i++;
		 }
		 return out;
	}
	
	@GET
	@Path("/annulla/{codice}/")
	public String Annulla(@PathParam("codice") String codice){
		String out = "-2";
		boolean continua = true;
		int i = 0;
		while(i < db.prenotationList.size() && continua){
			 if(db.prenotationList.get(i).codice.equals(codice)){
				 continua = false;
				 db.prenotationList.remove(i);
				 incrementaPostiDisponibili(codice);
				 out = "Prenotazione annullata con successo!!!";
			 }
			 i++;
		}
		return out;
	}
	
	private void incrementaPostiDisponibili(String cod){
		String[] s = cod.split("_");
		String nome = s[0] + "_" + s[1];
		boolean continua = true;
		int i = 0;
		while(i < db.parkingList.size() && continua){
			 if(db.parkingList.get(i).getNome().equals(nome)){
				 continua = false;
				 db.parkingList.get(i).incPosti();
			 }
			 i++;
		}
	}
	
	private String generatePrenotation(String nome){
		Date d = new Date();
		Calendar cal = Calendar.getInstance();
		String data = cal.get(Calendar.DAY_OF_MONTH) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
		String ora = cal.get(Calendar.HOUR) + ":" + cal.get(Calendar.MINUTE);
		String codice = nome +"_"+ d.getTime();
		db.prenotationList.add(new Prenotazione(data,ora,codice));
		return  codice;
	}
	
	private class Worker extends TimerTask{

		@Override
		public synchronized void run() {
			ArrayList<Prenotazione> array = new ArrayList<Prenotazione>();
			Calendar cal = Calendar.getInstance();
			String data = cal.get(Calendar.DAY_OF_MONTH) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
			int size = db.prenotationList.size();
			
			for(int i = 0; i < size; i++){
				if(db.prenotationList.get(i).data.equals(data)){
					String[] orario = db.prenotationList.get(i).ora.split(":");
					int minuti_List = Integer.parseInt(orario[0]) * 60 + Integer.parseInt(orario[1]);
					int minuti_attuali = cal.get(Calendar.HOUR) * 60 + cal.get(Calendar.MINUTE);
					int diff = minuti_attuali - minuti_List;
					if(diff < 60){
						array.add(db.prenotationList.get(i));
					}
					else
					{
						incrementaPostiDisponibili(db.prenotationList.get(i).codice);
					}
				}
				else
				{
					incrementaPostiDisponibili(db.prenotationList.get(i).codice);
				}
			}
			db.prenotationList.clear();
			db.prenotationList = array;
		}
	}
}